package handler

import (
	"fmt"
	"github.com/smartwalle/alipay/v3"
	"github.com/smartwalle/xid"
	"net/http"
	"week3/client/global"

	"github.com/zeromicro/go-zero/rest/httpx"
	"week3/client/internal/logic"
	"week3/client/internal/svc"
	"week3/client/internal/types"
)

func AliPayHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var tradeNo = fmt.Sprintf("%d", xid.Next())

		var p = alipay.TradePagePay{}
		p.ReturnURL = global.KServerDomain + "/alipay/callback"
		p.Subject = "支付测试:" + tradeNo
		p.OutTradeNo = r.FormValue("orderSn")
		p.TotalAmount = "10.00"
		p.ProductCode = "FAST_INSTANT_TRADE_PAY"

		url, _ := global.Client.TradePagePay(p)
		http.Redirect(w, r, url.String(), http.StatusTemporaryRedirect)
		fmt.Println(url.String(), "尚鑫平")
		//r.Form.Set("orderSn", url.String())
		var req types.AliPayReq
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		l := logic.NewAliPayLogic(r.Context(), svcCtx)
		resp, err := l.AliPay(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}
